<?php
	require_once('db-connection.php');
?>
<!DOCTYPE html>
<html>
	<head>
		<title>Upload Image</title>
	</head>
	<body>
		<form enctype="multipart/form-data" action="<?php echo $_SERVER['PHP_SELF'];?>" method="post">
			<label>Upload Image:</label>
			<input type="file" name="img" id="img" />
			<label for="alb">Album</label>
			<?php echo displayAlbumNames();?><br />
			<label for="descr">Description(optional)</label>
			<input type="text" name="descr" id="descr" /><br />
			<input type="submit" value="Upload" name="submit" />
		</form>		
	</body>
</html>

<?php

	function checkAndChangeName($name) {
		$allFileName = scandir('images');
		for($i = 2; $i < count($allFileName); $i++) {
			if($allFileName[$i] == $name) {
				$nameNoExt = substr($name, 0, strpos($name, '.'));
				$nameNoExt .= "_" . date('Y-m-d_H-i-s');
				$name = $nameNoExt . substr($name, strpos($name, '.'));
			}
		}
		return $name;
	}
			
	function uploadImg() {
		if(isset($_POST['submit'])) {
		$fileTempName = $_FILES["img"]["tmp_name"];
		$fileRealName = $_FILES["img"]["name"];
		$fileType = $_FILES["img"]["type"];
		
			if(is_uploaded_file($fileTempName)) {
				if(substr($fileType, 0, 6) == "image/") {
					$fileRealName = checkAndChangeName($fileRealName);
					if(move_uploaded_file($fileTempName, "images/$fileRealName")) {
						echo "<p> Img successfully uploaded </p>";
						return $fileRealName;
					}
					else {
						echo "<p> There was a problem uploading the image </p>";
					}
				}
				else {
					echo "<p> Please choose an IMAGE! </p>";
				}
			}
		}
	}
			
	function displayAlbumNames() {	
		$albumNames = mysql_query("select name, albumId from albums");
		$html = "<select name='album' id='alb'>";
		while($row = mysql_fetch_row($albumNames)) {
			$value = $row[0];
			$id = $row[1];
			$html .= "<option value='$id'>$value</option>";
		}
		$html .= "</select>";
		
		return $html;
	}
	function uploadImgAndAddToDB() {
		if(isset($_POST['submit'])) {
			$name = uploadImg();
			if(isset($name)) {
				$descr = $_POST["descr"];
				$albId = $_POST["album"];
				$imgIntoDB = mysql_query("insert into images(name, description) values('$name', '$descr');")
				or die("Could not insert the Image into the database " . mysql_error());
				$getImgId = mysql_query("select max(imgId) from images;");
				$row = mysql_fetch_row($getImgId);
				$imgId = $row[0];
				$imgAlbRel = mysql_query("insert into album_img_rel values('$albId', '$imgId');");
			}
		}
	}
			
	uploadImgAndAddToDB();
?>